//
//  WZFacePerceptionController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 2016/10/10.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "WZFacePerceptionController.h"
#import "FaceppPerson.h"
#import "FaceppGroup.h"
#import "FaceppClient.h"
#import "FaceppTrainer.h"
#import "FaceppResult.h"
#import "FaceppDetection.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "CAccountMgr.h"
#import "CAccountModel.h"
#import "WZCollectionViewCell.h"
#import "KKPhotoPickerManager.h"
#import <sys/utsname.h>

#define Max_FacePerception_PhotoCount 3
#define imageSize (160 * 0.5)
#define FacePerception_imagePath_KEY @"FacePerception_imagePath_KEY"
#define Face_ID @"Face_ID"

//static CGFloat imageSize = 80;

@interface WZFacePerceptionController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, UICollectionViewDelegate, UICollectionViewDataSource>

//@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
//@property(nonatomic,strong) UIImageView *screenshot;
@property(nonatomic,strong) CContactModel *currentUser;
@property (strong, nonatomic) CAccountModel *currentAcc;
@property (nonatomic,  copy) NSString *companyName;
@property (nonatomic,  copy) NSString *faceId;
@property (nonatomic, assign) NSInteger faceCount;
@property (nonatomic, strong) UIImage *photoImage;
@property (nonatomic, strong) NSMutableArray *photoArray;
@property (nonatomic, strong) UICollectionView *collectionView; //添加图片,每个cell内有一个imageView
@property (nonatomic, strong) NSMutableArray *imageArray;

@property (nonatomic, copy) NSString *imagePath;
@property (weak,   nonatomic) UIButton *confirmBtn;
@property (strong, nonatomic) NSMutableDictionary *pathDic;
@property (strong, nonatomic) NSMutableDictionary *faceIdDic;
//@property (strong, nonatomic) NSMutableArray *faceIdArray;
@property (assign, nonatomic) BOOL isSave;
@property (weak,   nonatomic) UIButton *cancelBtn;
@property (strong, nonatomic) NSMutableArray *faceIDArray;


@end

@implementation WZFacePerceptionController


static NSString *collectionViewCellId = @"collectionViewCellId";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setFacePerceptionAccountInfo];
    
    [self setUpData];
    
    [self setCollectionView];
    
    [self setUpUI];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self checkGroup];
}

- (void)setUpData {
//    _faceIDArray = [NSMutableArray array];
//    _faceIdDic = [NSMutableDictionary dictionary];
    for (NSInteger i = 0; i < 3; i++) {
        UIImage *image = [self fetchImageFromSanBoxWithIndexPath:i];
        [_photoArray addObject:[self fixOrientation:image]];
    }
}


- (void)setFacePerceptionAccountInfo {
    
    self.currentUser = [[[CContactMgr alloc]init] loadCurContact];
    self.currentAcc = [[[CAccountMgr alloc] init] getRecentlyLoginAccount];
    NSRange range = [_currentAcc.loginName rangeOfString:@"@"];
    self.companyName = [_currentAcc.loginName substringFromIndex:range.location+1];
    NSRange range1 = [self.companyName rangeOfString:@"."];
    self.companyName = [self.companyName substringToIndex:range1.location];
}

#pragma mark  UICollectionView数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 3;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    WZCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionViewCellId forIndexPath:indexPath];
    [self addAndSetSubViews:cell indexPath:indexPath];
    
    
    //添加子控件,设置布局与控件图片
//    BOOL isSave = [[NSUserDefaults standardUserDefaults] boolForKey:@"saveImage"];
//    if (!isSave) {
//        
//    } else {
//        cell.cancleBtn.hidden = YES;
//        UIImage *image = [self fetchImageFromSanBoxWithIndexPath:indexPath.item];
//        [self addCancelBtn:cell indextPath:indexPath];
//        cell.imageView.image = image;
////        [self addAndSetSubViews:cell indexPath:indexPath];
//    }
    
    return cell;
}

#pragma mark 添加cell 上的子控件

- (void)addAndSetSubViews:(WZCollectionViewCell *)cell indexPath:(NSIndexPath *)indexPath{
    //清空子控件,解决重用问题
    NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
    for (UIView *subview in subviews) {
        [subview removeFromSuperview];
    }
    UIImageView *imageView = [[UIImageView alloc]init];
    [cell.contentView addSubview:imageView];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.layer.masksToBounds = YES;
    imageView.image = [UIImage imageNamed:@"face_add_icon"];
    imageView.userInteractionEnabled = YES;
    UILongPressGestureRecognizer *longPressGS = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGSAction)];
    [imageView addGestureRecognizer:longPressGS];
    
    // 表示cell 是否可以点击
    cell.tag = 11;
    cell.imageView = imageView;
    cell.backgroundColor = [UIColor whiteColor];
    
    UIButton *cancleBtn = [[UIButton alloc]init];
    cell.cancleBtn = cancleBtn;
    [cell.contentView addSubview: cancleBtn];
    [cancleBtn setImage:[UIImage imageNamed:@"Faceperception_Delete_photo"] forState:UIControlStateNormal];
    cancleBtn.hidden = YES;
    cell.cancleBtn.tag = indexPath.row;
    [cell.cancleBtn addTarget:self action:@selector(cancleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.imageView.frame = CGRectMake(0, 0, imageSize, imageSize);
    cell.cancleBtn.frame = CGRectMake(imageSize - 20, 0, 20, 20);
    
    if (self.imageArray.count > indexPath.row) {
        if ([self.imageArray[indexPath.row] isKindOfClass:[UIImage class]]) {
            cell.imageView.image = nil;
            cell.imageView.image = self.imageArray[indexPath.row];
            cell.cancleBtn.hidden = NO;
            cell.tag = 10;
        }
    }
}


- (void)longPressGSAction {
    // TODO: 显示删除按钮
    WZLog(@"按钮显示");
}


#pragma mark  collectionView代理方法,添加照片
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    __weak typeof(self) weakSelf = self;
    if ([collectionView cellForItemAtIndexPath:indexPath].tag == 11) {
        [[KKPhotoPickerManager shareInstace] showActionSheetInView:self.view fromController:self completionBlock:^(NSMutableArray *imageArray) {
            for (NSInteger i = 0; i<imageArray.count; i++) {
                if (self.imageArray.count < Max_FacePerception_PhotoCount) {
                    UIImage *image = imageArray[i];
                    // 上传照片
                    [weakSelf upImageWithImage:image imageIndexPath:indexPath];
                }
            }
            [self.collectionView reloadData];
        }];
    }
}


// 访问相机

- (void)achieveCamera {
    
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [MBProgressHUD showError:@"相机不可用"];
        return;
    }
    
    UIImagePickerController *imagePicker = [UIImagePickerController new];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    imagePicker.delegate = self;
    
    [self presentViewController:imagePicker animated:YES completion:nil];
}


#pragma mark - 修复照片

- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}


-(void)checkGroup
{
    
    FaceppResult *result = [[[FaceppGroup alloc]init] getInfoWithGroupName:self.companyName orGroupId:nil];
    if (!result.success) {
        if (result.content == nil) {
            [MBProgressHUD showError:@"网络错误 请稍后再试"];
            UIView *view = [[UIView alloc]init];
            view.backgroundColor = [UIColor clearColor];
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.left.top.bottom.mas_equalTo(0);
            }];
        }
        else
        {
            FaceppResult *result = [[[FaceppGroup alloc]init] createWithGroupName:self.companyName];
            if (result.success) {
                [self checkPerson];
            }
        }
    }
    else
    {
        [self checkPerson];
    }
    
}
-(void)checkPerson
{
    FaceppResult *result  = [[[FaceppPerson alloc]init] getInfoWithPersonName:self.currentUser.UserName orPersonId:nil];
    if (!result.success) {
        [[[FaceppPerson alloc]init] createWithPersonName:self.currentUser.UserName andFaceId:nil andTag:nil andGroupId:nil orGroupName:@[self.companyName]];
    } else {
        [MBProgressHUD showSuccess:@"您已经上传人脸"];
    }
}



-(void)trainGroup
{
    [[[FaceppTrainer alloc]init] trainAsynchronouslyWithId:nil orName:self.companyName andType:FaceppTrainIdentify];
}
-(void)trainPerson
{
    [[[FaceppTrainer alloc]init] trainAsynchronouslyWithId:nil orName:self.currentUser.UserName     andType:FaceppTrainVerify];
}


#pragma mark - 上传到face++

-(void)upImageWithImage:(UIImage *)selectImage imageIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showMessage:@"人脸上传中。。。"];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImage *image = [weakSelf fixOrientation:selectImage];
        NSData *data = nil;
        
        if ([self getCurretnDeviceVersion] > 7) {
            data = UIImageJPEGRepresentation(image, 0.5);
        } else {
            data = UIImageJPEGRepresentation(image, 1);
        }
        FaceppResult *result =  [[[FaceppDetection alloc]init] detectWithURL:nil orImageData:data mode:FaceppDetectionModeOneFace];
        if (result.success) {
            NSArray *faceArray = result.content[@"face"] ;
            if (faceArray.count>0) {
                _faceId = faceArray.firstObject[@"face_id"];
                FaceppResult *result = [[[FaceppPerson alloc]init] addFaceWithPersonName:self.currentUser.UserName orPersonId:nil andFaceId:@[self.faceId]];
                if (result.success) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [MBProgressHUD hideHUD];
                        [MBProgressHUD showSuccess:@"上传成功"];
                        [_imageArray addObject:image];
                        
                        [self.faceIdDic setObject:_faceId forKey:@"faceID"];
                        [self.faceIDArray addObject:_faceId];
                        
                        [_collectionView reloadData];

                        [weakSelf saveImage:image InSanBoxWithIndexPath:_faceCount];
                        
                        _faceCount++;
                    });
                    
                    [weakSelf trainPerson];
                    [weakSelf trainGroup];
                }
            }
            else
            { dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"添加人脸失败"];
            });
            }
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"人脸认证失败 请重新录制"];
            });
        }
        
    });
}


#pragma mark  删除人脸

- (void)cancleBtnClick:(UIButton *)sender{
    
    // 获取faceID
    NSString *faceID = _faceIDArray[sender.tag];
    
    if (sender.tag < self.imageArray.count) {
        
        [MBProgressHUD showMessage:@"删除人脸中。。。"];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            FaceppResult *removeResult = [[[FaceppPerson alloc] init] removeFaceWithPersonName:_currentUser.UserName orPersonId:nil andFaceId:@[faceID]];
            if (removeResult.success) {
                dispatch_async(dispatch_get_main_queue(), ^{
    
                    [_imageArray removeObjectAtIndex:sender.tag];
                    sender.hidden = YES;
                    [_collectionView reloadData];
                    [MBProgressHUD hideHUD];
                    [MBProgressHUD showSuccess:@"删除人脸成功!"];
                    [self.collectionView reloadData];
                    
                    // 删除本地图片资源
//                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//    
//                        [self deleteImageAtIndexPath:0];
//                    });
    
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD hideHUD];
                    [MBProgressHUD showError:@"删除人脸失败,请重试!"];
                });
            }
        });
    }
}



#pragma mark -
#pragma mark 上传到服务器

- (void)confirmBtnDidClick {
    
    // TODO: 提交人事审核
    BOOL facePerception = YES;
    [[NSUserDefaults standardUserDefaults] setBool:facePerception forKey:@"facePerception_Key"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}


// 保存图片到沙盒

- (void)saveImage:(UIImage *)image InSanBoxWithIndexPath:(NSInteger)indexPath {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%ld.png", indexPath]];   // 保存文件的名称
    
    [UIImagePNGRepresentation(image)writeToFile:filePath atomically:YES];
}

#pragma mark -
#pragma mark 本地图片处理

// 保存图片的路径到字典
- (void)dicPathsWithIndexPath:(NSInteger)indexPath
{
    NSMutableArray *specialArr = [[NSMutableArray alloc] initWithCapacity:0];
    
    _pathDic = [[NSMutableDictionary alloc]init];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%ld.png", indexPath]];   // 保存文件的名称
    
    [_pathDic setObject:filePath forKey:[NSString stringWithFormat:@"img_%ld", indexPath]];
    [specialArr addObject:_pathDic];
}

// 根据字典路径获取图片
- (UIImage *)fetchImageFromSanBoxWithIndexPath:(NSInteger)indexPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%ld.png", indexPath]];   // 保存文件的名称
    UIImage *img = [UIImage imageWithContentsOfFile:filePath];
    return img;
}

#pragma mark 删除沙盒图片

- (BOOL)deleteImageAtIndexPath:(NSInteger)index;
{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%ld.png", index]];
    
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        return  [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
    }
    
    return NO;
}

#pragma mark  设置CollectionView
- (void)setCollectionView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(imageSize, imageSize);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumInteritemSpacing = 25;
    layout.minimumLineSpacing = 25;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 60, HARDWARE_SCREEN_WIDTH, 160 * 0.5) collectionViewLayout:layout];
    self.collectionView = collectionView;
    [self.view addSubview:collectionView];
    [collectionView setBackgroundColor:WhiteColor];
    [self.collectionView registerClass:[WZCollectionViewCell class] forCellWithReuseIdentifier:collectionViewCellId];
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 15, 0, 15);
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
}


- (NSInteger)getCurretnDeviceVersion {
    
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString* code = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    NSArray *array = [code componentsSeparatedByString:@","];
    NSString *name = array.firstObject;
    NSRange range = [name rangeOfString:@"iPhone"];
    NSString *number = [name substringFromIndex:range.length];
    return number.integerValue;
}


- (void)setUpUI {
    self.navigationItem.title = @"人脸识别认证";
    self.view.backgroundColor = [UIColor whiteColor];
    
    UILabel *label = [[UILabel alloc] init];
    [self.view addSubview:label];
    label.font = [UIFont systemFontOfSize:16];
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = RGBCOLORWITH16COLOR(0x999999);
    label.text = @"请您上传三张清晰的个人头像";
    [label sizeToFit];
    [label adjustsFontSizeToFitWidth];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).mas_offset(15);
        make.top.equalTo(self.view).mas_offset(22);
    }];
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.confirmBtn = confirmBtn;
    [self.view addSubview:confirmBtn];
    //    [confirmBtn setBackgroundImage:[UIImage imageNamed:@"Button-moren"] forState:UIControlStateNormal];
    //    [confirmBtn setBackgroundImage:[UIImage imageNamed:@"button-anxia"] forState:UIControlStateHighlighted];
    
    [confirmBtn setBackgroundColor:RGBCOLORWITH16COLOR(0xdadada)];
    [confirmBtn setTitle:@"提交" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:WhiteColor forState:UIControlStateNormal];
    [confirmBtn addTarget:self action:@selector(confirmBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionView.mas_bottom).mas_offset(58);
        make.left.equalTo(self.view).mas_offset(15);
        make.right.equalTo(self.view).mas_offset(-15);
        make.height.mas_equalTo(45);
    }];
}


- (NSMutableArray *)photoArray {
    
    if (!_photoArray) {
        _photoArray = [NSMutableArray array];
    }
    return _photoArray;
}


- (NSMutableArray *)faceIDArray {
    if (!_faceIDArray) {
        _faceIDArray = [NSMutableArray array];
    }
    return _faceIDArray;
}

- (NSMutableArray *)imageArray {
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

- (NSMutableDictionary *)faceIdDic {
    if (!_faceIdDic) {
        _faceIdDic = [NSMutableDictionary dictionary];
    }
    return _faceIdDic;
}


@end
